package com.ruoyi.elastic.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;


@Service
public class ESService {

    private static final Logger log = LoggerFactory.getLogger(ESService.class);

    @Autowired
    private RestTemplate restTemplate;

    @Value("${spring.elasticsearch.rest.uris}")
    private String hostIp;

    private final String indexName="skuinfo";

    //通过restClient直接发送请求
    public JSON searchQuery(String indexName,String DSL){
        HttpHeaders headers = new HttpHeaders();
        //设置类型
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        HttpEntity<String> formEntity = new HttpEntity<>(DSL, headers);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity("http://"+hostIp+"/"+indexName+"/_search", formEntity, String.class);
        log.info(responseEntity.getBody());
        return JSONObject.parseObject(responseEntity.getBody());
    }



}
